package ru.vsu.cs.pm.components.tree;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.markup.html.tree.table.IColumn;
import org.apache.wicket.extensions.markup.html.tree.table.TreeTable;
import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.model.IModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import ru.vsu.cs.pm.beans.ItemManager;
import ru.vsu.cs.pm.models.Item;

import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import java.util.List;

/**
 * User: ohodyakov
 * Date: 27.12.2010
 * Time: 12:46:32
 */
public class MutableTreeTable extends TreeTable {

    @SpringBean
    private ItemManager itemManager;

    public MutableTreeTable(String id, IModel model, IColumn[] columns) {
        super(id, model, columns);
        InjectorHolder.getInjector().inject(this);
    }

    @Override
    protected void onJunctionLinkClicked(AjaxRequestTarget target, TreeNode node) {
        if (node.getChildCount() != 0) {
            return;
        }
        MutableTreeNode treeNode = (MutableTreeNode) node;
        Item parentItem = (Item) treeNode.getUserObject();
        // Retrieve the records from Database
        if (parentItem != null) {
            List<Item> childrenItems = itemManager.getChildrenItems(parentItem);
            MutableTreeNode child = null;
            for (Item item : childrenItems) {
                child = new MutableTreeNode(item);
                child.setAllowsChildren(item.getChildrenCount() > 0);
                treeNode.add(child);
            }
            getTreeState().expandNode(treeNode);
        } else if (treeNode != null) {
            treeNode.setAllowsChildren(false);
        }
    }

    public void expandParent(TreeNode node) {
        if (node.getChildCount() != 0) {
            return;
        }
        MutableTreeNode treeNode = (MutableTreeNode) node;
        Item parentItem = (Item) treeNode.getUserObject();
        // Retrieve the records from Database
        if (parentItem != null) {
            List<Item> childrenItems = itemManager.getChildrenItems(parentItem);
            MutableTreeNode child = null;
            for (Item item : childrenItems) {
                child = new MutableTreeNode(item);
                child.setAllowsChildren(item.getChildrenCount() > 0);
                treeNode.add(child);
            }
            getTreeState().expandNode(treeNode);
        } else if (treeNode != null) {
            treeNode.setAllowsChildren(false);
        }
    }
}
